package cc.rengu.redp.bizimpl.csmc.service.impl;

import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.request.MchntStatusManageRequest;
import cc.rengu.igas.bomp.facade.response.MchntStatusManageResponse;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.csmc.dao.CNoTxnRegMapper;
import cc.rengu.redp.bizimpl.csmc.domain.CNoTxnReg;
import cc.rengu.redp.bizimpl.csmc.service.ICNoTxnRegService;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BTermInfo;
import cc.rengu.redp.bizimpl.upmp.domain.QrcodeInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntBaseInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author lizk
 */
@Service
@DS("csmc")
public class CNoTxnRegServiceImpl extends ServiceImpl<CNoTxnRegMapper, CNoTxnReg> implements ICNoTxnRegService {

    @Autowired
    private IBTermInfoService termInfoService;
    @Autowired
    private IQrcodeInfoService codeInfoService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IUpmpSysSeqService sysSeqService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntManageService bompMchntManageService;

    @Override
    public IPage<CNoTxnReg> findByPage(QueryRequest queryRequest, CNoTxnReg noTxnReg, String statisType) {
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        try {
            LambdaQueryWrapper<CNoTxnReg> queryWrapper = new LambdaQueryWrapper<>();

            if (statisType.equals("00")) {
                if (!StringUtils.isEmpty(noTxnReg.getStatisType())) {
                    queryWrapper.eq(CNoTxnReg::getStatisType, noTxnReg.getStatisType());
                }
                if (!StringUtils.isEmpty(noTxnReg.getMchntNo())) {
                    queryWrapper.eq(CNoTxnReg::getMchntNo, noTxnReg.getMchntNo());
                }
                if (!StringUtils.isEmpty(noTxnReg.getMchntStatus())) {
                    queryWrapper.eq(CNoTxnReg::getMchntStatus, noTxnReg.getMchntStatus());
                }
                if (!StringUtils.isEmpty(noTxnReg.getStartDate()) && !StringUtils.isEmpty(noTxnReg.getEndDate())) {
                    queryWrapper.ge(CNoTxnReg::getEndTxnTime, noTxnReg.getStartDate()).le(CNoTxnReg::getEndTxnTime, noTxnReg.getEndDate());
                }
            } else {
                if (!StringUtils.isEmpty(noTxnReg.getDateArea())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    Date dt = new Date();
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(dt);
                    rightNow.add(Calendar.MONTH, -Integer.parseInt(noTxnReg.getDateArea()));
                    Date dt1 = rightNow.getTime();
                    String startTime = sdf.format(dt1);
                    String endTime = sdf.format(dt);
                    queryWrapper.ge(CNoTxnReg::getEndTxnTime, startTime).le(CNoTxnReg::getEndTxnTime, endTime);
                }
                if (!StringUtils.isEmpty(noTxnReg.getAcqInstCode())) {
                    queryWrapper.and(i -> i.like(CNoTxnReg::getAcqInstCode, noTxnReg.getAcqInstCode()));
                }
                if (!StringUtils.isEmpty(noTxnReg.getTermNo())) {
                    queryWrapper.and(i -> i.like(CNoTxnReg::getTermNo, noTxnReg.getTermNo()));
                }
                if (!StringUtils.isEmpty(noTxnReg.getMchntNo())) {
                    queryWrapper.and(i -> i.like(CNoTxnReg::getMchntName, noTxnReg.getMchntName())
                            .or().like(CNoTxnReg::getMchntNo, noTxnReg.getMchntNo()));
                }
                if (!StringUtils.isEmpty(noTxnReg.getStatisType())) {
                    queryWrapper.eq(CNoTxnReg::getStatisType, noTxnReg.getStatisType());
                }
                if (!StringUtils.isEmpty(noTxnReg.getStatus())) {
                    String term_no = "";
                    List<BTermInfo> termInfos = termInfoService.selectTermNo(noTxnReg.getStatus(), noTxnReg.getInstId());

                    if (termInfos != null && termInfos.size() > 0) {
                        for (BTermInfo termInfo : termInfos) {
                            term_no += ",'" + termInfo.getTermNo() + "'";
                        }
                    }

                    String qr_status = "";
                    if ("01".equals(noTxnReg.getStatus())) {
                        qr_status = "00";
                    } else if ("02".equals(noTxnReg.getStatus())) {
                        qr_status = "01";
                    }

                    List<QrcodeInfo> qrcodeInfos = codeInfoService.selectQrCode(qr_status, noTxnReg.getInstId());
                    for (QrcodeInfo qrcodeInfo : qrcodeInfos) {
                        term_no += ",'" + qrcodeInfo.getQrCode() + "'";
                    }

                    if (!"".equals(term_no)) {
                        term_no = term_no.substring(1);
                        queryWrapper.in(CNoTxnReg::getTermNo, term_no);
                    }
                }

                if (null != user && user.isAdmin()) {
                    if (!StringUtils.isEmpty(noTxnReg.getInstId())) {
                        queryWrapper.eq(CNoTxnReg::getInstId, noTxnReg.getInstId());
                    }
                } else {
                    queryWrapper.eq(CNoTxnReg::getInstId, user.getInstId());
                }


            }
            if (statisType.equals("00")) {
                queryWrapper.eq(CNoTxnReg::getStatisType, "00");
            } else {
                queryWrapper.eq(CNoTxnReg::getStatisType, "01");
            }
            Page<CNoTxnReg> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            Page<CNoTxnReg> infoPage = this.page(page, queryWrapper);
//            System.out.println(infoPage.getRecords().get(0).getStatisType()+"   ****   数据");

            //对查询结果进一步封装
            if (statisType.equals("00")) {
                for (CNoTxnReg record : infoPage.getRecords()) {
                    String code = record.getAcqInstCode();
                    String orgName = organizationService.selectOrgByCode(code);
                    record.setAcqInstName(orgName);

                    String mchntNo = record.getMchntNo();
                    String mchntParam = bMchntBaseInfoService.selectByMchntNo(mchntNo);
                    if (!mchntParam.equals("")) {
                        String[] str = mchntParam.split(";");
                        record.setMchntType(str[0]);
                        record.setManagerName(str[1]);
                        record.setMchntExpandTime(str[2]);
                        record.setMchntContactName(str[3]);
                        record.setMchntContactPhone(str[4]);
                        record.setAuditStatus(str[6]);
                    }
                }

            } else {
                for (CNoTxnReg record : infoPage.getRecords()) {
                    String mchntNo = record.getMchntNo();
                    UpmpBMchntBaseInfo byMchntNo = bMchntBaseInfoService.findByMchntNo(mchntNo);
                    record.setMchntType(byMchntNo.getMchntType());

                    String code = record.getAcqInstCode();
                    String orgName = organizationService.selectOrgByCode(code);
                    record.setAcqInstName(orgName);

                    if (record.getStatisType().equals("01")) {
                        String status = "";
                        if (null != record.getTermNo()) {
                            BTermInfo termInfo = termInfoService.selectByTermNo(record.getTermNo());
                            if (!StringUtils.isEmpty(termInfo)) {
                                status = termInfo.getTermStatus() + ";" + termInfo.getAuditStatus() + ";" + termInfo.getLastUpdateTime();
                            }
                        }
                        if (!status.equals("")) {
                            String[] str = status.split(";");
                            record.setStatus(str[0]);
                            record.setAuditStatus(str[1]);
                            if (str[0].equals("02")) {
                                record.setStopDate(str[2]);
                            }
                        }
                    } else if (record.getStatisType().equals("02")) {
                        String status = "";
                        if (null != record.getTermNo()) {
                            QrcodeInfo qrcodeInfo = codeInfoService.selectByQrCode(record.getTermNo());
                            if (!StringUtils.isEmpty(qrcodeInfo)) {
                                status = qrcodeInfo.getQrStatus() + ";" + qrcodeInfo.getStopTime();
                            }
                        }
                        if (!status.equals("")) {
                            String sta = "";
                            String[] str = status.split(";");
                            if (str[0].equals("00")) {
                                sta = "01";
                            }
                            if (str[0].equals("01")) {
                                sta = "02";
                            }
                            record.setStatus(sta);
                            record.setAuditStatus("");//暂时没有
                            if (sta.equals("02")) {
                                record.setStopDate(str[2]);
                            }
                        }
                    }

                }
            }

            return infoPage;
        } catch (Exception e) {
            log.error("获取卡号黑名单信息失败", e);
            return null;
        }
    }

    @Override
    public void updateNoTxnReg(CNoTxnReg noTxnReg) throws RedpException {

        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        // 8位日期
        String date17 = DateUtils.formatDate(new Date(), DateUtils.FULL_SEQ_FORMAT);
        //获取终端编号
        String traceNo = noTxnReg.getInstId() + "MCMP" + date17 + String.format("%08d", Integer.parseInt(sysSeqService
                .updateParamValue(BusinessContainer.COMM_PARAM_CODE, "MER_ORDER", null)));

        String flag = noTxnReg.getOptFlag();
        if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
            if (noTxnReg.getStatisType().equals("01")) {//终端
                if (org.apache.commons.lang3.StringUtils.isBlank(noTxnReg.getTermNo())) {
                    throw new RedpException("终端编号不可为空");
                }
                updateTermStatus(noTxnReg.getTermNo(), "02", "22", lastUpddt, user.getId());
            } else if (noTxnReg.getStatisType().equals("02")) {//二维码
                if (org.apache.commons.lang3.StringUtils.isBlank(noTxnReg.getTermNo())) {
                    throw new RedpException("二维码编号不可为空");
                }
                updateQrcodeInfoStatus(noTxnReg.getTermNo(), "01", "", lastUpddt, user.getId());
            } else {
                if (org.apache.commons.lang3.StringUtils.isBlank(noTxnReg.getMchntNo())) {
                    throw new RedpException("商户号不可为空");
                }
                updateMchntStatus(noTxnReg, "02", user, bompMchntManageService, traceNo, "noTxnReg:stop");
            }
        } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {
            if (noTxnReg.getStatisType().equals("01")) {//终端
                if (org.apache.commons.lang3.StringUtils.isBlank(noTxnReg.getTermNo())) {
                    throw new RedpException("终端编号不可为空");
                }
                updateTermStatus(noTxnReg.getTermNo(), "01", "32", lastUpddt, user.getId());
            } else if (noTxnReg.getStatisType().equals("02")) {//二维码
                if (org.apache.commons.lang3.StringUtils.isBlank(noTxnReg.getTermNo())) {
                    throw new RedpException("二维码编号不可为空");
                }
                updateQrcodeInfoStatus(noTxnReg.getTermNo(), "00", "", lastUpddt, user.getId());
            } else {
                if (org.apache.commons.lang3.StringUtils.isBlank(noTxnReg.getMchntNo())) {
                    throw new RedpException("商户号不可为空");
                }
                updateMchntStatus(noTxnReg, "03", user, bompMchntManageService, traceNo, "noTxnReg:use");
            }
        }

    }

    private void updateMchntStatus(CNoTxnReg entity, String oprType, UpmpUserInfoVO user, BompMchntManageService bompMchntManageService, String traceNo, String code) throws RedpException {

        CommonUtils.validateUserInst(entity.getInstId(), user);
        MchntStatusManageRequest req = new MchntStatusManageRequest();
        String checked = "";
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), code);

        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            checked = "1";
        } else {
            checked = "0";
        }

        if ("02".equals(oprType)) {
            if (org.apache.commons.lang3.StringUtils.isBlank(entity.getStopReason())) {
                throw new RedpException("请输入停用原因");
            }
        }

        req.setUserId(user.getId());
        req.setMchntNo(entity.getMchntNo());
        req.setOprType(oprType);
        req.setMchntStopReason(entity.getStopReason());
        req.setChecked(checked);
        req.setOprMenuId("20000030");
        req.setOprMenuName("商户管理:间联商户管理");
        req.setWebNextUrl("");
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntStatusManage.getType(), entity.getInstId(), null));

        log.error("商户状态管理" + BompTxnNumEnum.mchntStatusManage.getDesc() + "请求报文：" + JSON.toJSONString(req));
        try {
            Result<MchntStatusManageResponse> response = bompMchntManageService.mchntStatusManage(req);
            log.error("商户状态管理" + BompTxnNumEnum.mchntStatusManage.getDesc() + "返回报文：" + JSON.toJSONString(response));
            MchntStatusManageResponse resp = response.getResult();
            if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                log.error("商户状态管理" + BompTxnNumEnum.mchntStatusManage.getDesc() + "交易成功");
            } else {
                log.error("商户状态管理" + BompTxnNumEnum.mchntStatusManage.getDesc() + "交易失败");
            }
        } catch (Exception e) {
            log.error("商户状态管理：，" + BompTxnNumEnum.mchntStatusManage.getDesc() + "交易出现异常，异常信息：" + e.getMessage(), e);
            throw new RedpException("商户状态管理接口调用失败！");
        }

    }


    public void updateQrcodeInfoStatus(String no, String qrStatus, String stopReason, String lastUpddt, String lastOprId) throws RedpException {
        LambdaUpdateWrapper<QrcodeInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(QrcodeInfo::getQrCode, no);
        QrcodeInfo qrcodeInfo = new QrcodeInfo();
        qrcodeInfo.setQrStatus(qrStatus);
        qrcodeInfo.setLastOprId(lastOprId);
        qrcodeInfo.setLastUpdateTime(lastUpddt);
        qrcodeInfo.setStopTime(lastUpddt);
        if (null != stopReason && !stopReason.equals("")) {
            qrcodeInfo.setStopReason(stopReason);
        }
        codeInfoService.update(qrcodeInfo, wrapper);
    }


    public void updateTermStatus(String no, String termStatus, String auditStatus, String lastUpddt, String lastOprId) throws RedpException {
        LambdaUpdateWrapper<BTermInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(BTermInfo::getTermNo, no);
        BTermInfo termInfo = new BTermInfo();
        termInfo.setTermStatus(termStatus);
        termInfo.setAuditStatus(auditStatus);
        termInfo.setLastUpdateTime(lastUpddt);
        termInfo.setLastOprId(lastOprId);
        termInfoService.update(termInfo, wrapper);
    }

}
